import BaseBackground from "@plugin/BaseBackground";
import EnhanceUseNavigate from "@plugin/EnhanceUseNavigate";
import Modal from "@plugin/Modal";
import { GoRegister } from "@utils";
import copy from "copy-to-clipboard";
import React, { Component } from "react";
import { Toast } from "react-vant";
import { IsRegistered, getChannel, parseLinkWithHash } from "../../../utils";
import styles from "./index.module.scss";

import VideoPoster from "@/assets/poster.jpg";
import BackgroundImg from "@assets/bg02.jpg";
import PlayIcon from "@assets/play.png";
import RegisterButton from "@assets/register_button.png";
import RegisterRmk from "@assets/register_button_rmk.png";
import SelectGift2 from "@assets/select_gift_1.png";
import SelectButton from "@assets/select_gift_button.png";
import CustomizedButton from "@assets/select_gift_button2.png";
import ShareButton from "@assets/share_button.png";
import VideoCover from "@assets/video_cover.png";
import ShareCom from "../../../plugin/ShareMask/index";

import { getConfigData, getVideoRender } from "@api";
import {
	CampaignIds,
	HaPopupClosed,
	HaPopupOpen,
	getHaPageTypeWithShare,
} from "../../../utils/ha.common";

class Index extends Component {
	constructor(props) {
		const search = new URLSearchParams(window.location.search);
		super(props);

		this.state = {
			registered: IsRegistered(),
			isFromShare:
				search.get("isShare") || search.get("shareOpenid") ? true : false,
			showSelectGiftStatus: false,
			videoSrc: "",
			audioSrc: "",
			playStatus: false,
			type: undefined,
			taoLink: "",
			taskId: search.get("taskId"),
		};
		this.videoRef = "";
		this.shareRef = React.createRef();
	}

	// componentWillUnmount() {
	//   window?.wx?.miniProgram.postMessage({
	//     data: {
	//       type: "video",
	//       taskId: "",
	//     },
	//   });
	// }

	async componentDidMount() {
		// 加载淘宝链接
		getConfigData({ code: "TAO_LINK" }).then((res) => {
			if (res["state"] === "ok") {
				this.setState({
					taoLink: res["data"]["value"],
				});
			}
		});

		getVideoRender({ taskId: this.state.taskId }).then((res) => {
			const { data, state } = res; //data.type === 4 说明是定制视频 data.type === 2 说明是非定制
			if (state === "ok") {
				this.setState({
					type: data.type,
					videoSrc: data.mp4_url,
				});
			}
		});

		//传递消息给小程序
		this.posterMessageToMini();

		//根据小程序返回， 判读是否已注册。
		document.addEventListener("visibilitychange", () => {
			console.log("visibilitychange is in~");
			const hashParmas = parseLinkWithHash(window.location.href);
			console.log("hashParmas is", hashParmas);
			hashParmas?.memberId &&
				sessionStorage.setItem("memberid", hashParmas.memberId);

			this.setState({
				registered: IsRegistered(),
			});

			this.posterMessageToMini();
		});

		//CNY_活动一_视频页_页面访问
		window._ha("send", "action", "cny_activity1_videopage_view", {
			campaign_id: CampaignIds.activity1,
			channel: getChannel(),
			page_type: getHaPageTypeWithShare(),
		});
	}

	posterMessageToMini() {
		if (IsRegistered()) {
			window?.wx?.miniProgram.postMessage({
				data: {
					type: "video",
					taskId: this.state.taskId,
				},
			});
		}
	}

	handlerClick = () => {
		const { playStatus } = this.state;
		if (playStatus) {
			this.setState({
				playStatus: false,
			});

			this.videoRef.pause();
			// audioRef.pause();
			// audioPlay = false;
		} else {
			this.setState({
				playStatus: true,
			});

			this.videoRef.play();
			this.videoRef.addEventListener("ended", () => {
				this.setState({
					playStatus: false,
				});
			});
		}
	};

	handlerShare = () => {
		this.shareRef.open();
		HaPopupOpen(
			"SharePage",
			"cny_activity1_popupwindow_open",
			CampaignIds.activity1
		);
		window._ha(
			"send",
			"action",
			"cny_activity1_videopage_shareblessing_click",
			{
				campaign_id: CampaignIds.activity1,
				channel: getChannel(),
				page_type: "MemberVideoPage",
			}
		);
	};

	goRegiser = () => {
		const search = new URLSearchParams(window.location.search);

		GoRegister(
			`/pages/userPackage/FY2324_CNY_BeSpoke_Register?fromPage=${encodeURIComponent(
				window.location.href
			)}&taskId=${search.get("taskId")}`
		);

		window._ha("send", "action", "cny_activity1_videopage_register_click", {
			campaign_id: CampaignIds.activity1,
			channel: getChannel(),
			page_type: "NotMemberVideoPage",
		});
	};

	handlerSelectGift = () => {
		this.setState({
			showSelectGiftStatus: true,
		});

		HaPopupOpen(
			"GiftPopupWindow",
			"cny_activity1_popupwindow_open",
			CampaignIds.activity1
		);

		window._ha("send", "action", "cny_activity1_videopage_choosegift_click", {
			campaign_id: CampaignIds.activity1,
			channel: getChannel(),
			page_type: this.state.isFromShare
				? "ShareVideoPage"
				: IsRegistered()
				? "MemberVideoPage"
				: "NotMemberVideoPage",
		});
	};

	closeSelectModal = () => {
		this.setState({
			showSelectGiftStatus: false,
		});

		HaPopupClosed(
			"GiftPopupWindow",
			"cny_activity1_popupwindow_close",
			CampaignIds.activity1
		);
	};

	handlerClickSelectGift = () => {
		copy(this.state.taoLink);

		window._ha(
			"send",
			"action",
			"cny_activity1_giftpopupwindow_gotobuy_click",
			{
				campaign_id: CampaignIds.activity1,
				channel: getChannel(),
			}
		);
	};

	render() {
		const {
			registered,
			isFromShare,
			videoSrc,
			showSelectGiftStatus,
			playStatus,
		} = this.state;

		return (
			<>
				{!isFromShare && (
					<button
						className={styles.resetButtbon}
						onClick={() => {
							window._ha(
								"send",
								"action",
								"cny_activity1_videopage_makevideoagain_click",
								{
									campaign_id: CampaignIds.activity1,
									channel: getChannel(),
									page_type: getHaPageTypeWithShare(),
								}
							);
							this.props.navigate(-1);
						}}
					/>
				)}

				<BaseBackground
					hideLogo={true}
					backgroundImage={BackgroundImg}
					showFlag={true}
				>
					<div className={styles.video_box}>
						<div className={styles.videoContainer}>
							<video
								preload="auto"
								poster={VideoPoster}
								controls={false}
								playsInline
								ref={(video) => (this.videoRef = video)}
								className={styles.video}
								src={videoSrc}
							></video>
						</div>

						<img
							onClick={() => {
								if (playStatus) {
									this.handlerClick();
								}
							}}
							className={styles.video_cover}
							src={VideoCover}
							alt=""
						/>

						{playStatus ? (
							""
						) : (
							<img
								onClick={this.handlerClick}
								className={styles.play_icon}
								src={PlayIcon}
								alt=""
							/>
						)}
					</div>
					<div className={styles.video_footer}>
						<div
							className={`${styles.rmk} ${
								registered || isFromShare ? styles.add_margin : ""
							}`}
						>
							{this.state.type === 2 && "视频语音采用阿里云语音合成技术生成"}
						</div>

						{/* 来自分享 */}
						{isFromShare ? (
							<div className={styles.button_group}>
								<img
									onClick={() => {
										window._ha(
											"send",
											"action",
											"cny_activity1_videopage_gotomake_click",
											{
												campaign_id: CampaignIds.activity1,
												channel: getChannel(),
												page_type: "ShareVideoPage",
											}
										);

										this.props.navigate("/");
									}}
									src={CustomizedButton}
									className={styles.option_button}
									alt=""
								/>
								<img
									onClick={this.handlerSelectGift}
									src={SelectButton}
									className={styles.option_button}
									alt=""
								/>
							</div>
						) : (
							<div className={styles.button_group}>
								<img
									onClick={this.handlerSelectGift}
									src={SelectButton}
									className={styles.option_button}
									alt=""
								/>
								{registered ? (
									<img
										onClick={this.handlerShare}
										src={ShareButton}
										className={styles.option_button}
										alt=""
									/>
								) : (
									<div className={styles.option_button_out}>
										<img
											src={RegisterRmk}
											className={styles.register_rmk}
											alt=""
										/>
										<img
											onClick={this.goRegiser}
											src={RegisterButton}
											className={styles.option_button}
											alt=""
										/>
									</div>
								)}
							</div>
						)}
					</div>
				</BaseBackground>

				{showSelectGiftStatus ? (
					<Modal>
						<div className={styles.share_modal_box}>
							<div
								onClick={this.closeSelectModal}
								className={styles.share_modal_close_button}
							></div>

							<div className={styles.giftContainer}>
								<img src={SelectGift2} className={styles.share_modal} alt="" />
								<i
									className={styles.link1}
									onClick={() => {
										copy(
											"https://equity.tmall.com/tm?agentId=5a492ad194ba4d26&bc_fl_src=tmall_market_llb_1_2464696&llbPlatform=_pube&llbOsd=1"
										);
										Toast({
											message: "链接已复制\n请前往淘宝app搜索框粘贴打开",
											className: "upward-toast",
										});
									}}
								></i>
							</div>
						</div>
					</Modal>
				) : (
					""
				)}

				<ShareCom ref={(ref) => (this.shareRef = ref)} />
			</>
		);
	}
}

export default EnhanceUseNavigate(Index);
